/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.business.rest;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.annotation.Log;
import me.zhengjie.business.domain.PricPsn;
import me.zhengjie.business.service.PricPsnService;
import me.zhengjie.business.service.dto.PricPsnDto;
import me.zhengjie.business.service.dto.PricPsnQueryCriteria;
import me.zhengjie.business.service.dto.PricRegnDto;
import me.zhengjie.business.util.HttpNewMicProvince;
import me.zhengjie.business.util.SmUtilProvince;
import me.zhengjie.modules.system.service.DeptService;
import me.zhengjie.modules.system.service.dto.DeptDto;
import me.zhengjie.nmi.ChsInterfaceConfig;
import me.zhengjie.nmi.ChsUtil;
import me.zhengjie.utils.DateTimeUtil;
import me.zhengjie.utils.SecurityUtils;
import org.springframework.data.domain.Pageable;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://el-admin.vip
* @author xiahongbo
* @date 2025-01-06
**/
@Slf4j
@RestController
@RequiredArgsConstructor
@Api(tags = "护理员管理")
@RequestMapping("/api/pricPsn")
public class PricPsnController {

    private final PricPsnService pricPsnService;

    private final DeptService deptService;

    private final HttpNewMicProvince httpNewMicProvince;

    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('pricPsn:list')")
    public void exportPricPsn(HttpServletResponse response, PricPsnQueryCriteria criteria) throws IOException {
        criteria.setSfyx("1");
        pricPsnService.download(pricPsnService.queryAll(criteria), response);
    }

    @GetMapping
    @Log("查询护理员")
    @ApiOperation("查询护理员")
    @PreAuthorize("@el.check('pricPsn:list')")
    public ResponseEntity<Object> queryPricPsn(PricPsnQueryCriteria criteria, Pageable pageable){
        criteria.setSfyx("1");
        return new ResponseEntity<>(pricPsnService.queryAll(criteria,pageable),HttpStatus.OK);
    }

    @PostMapping
    @Log("新增护理员")
    @ApiOperation("新增护理员")
    @PreAuthorize("@el.check('pricPsn:add')")
    public ResponseEntity<Object> createPricPsn(@Validated @RequestBody PricPsn resources){


        log.info("createPricPsn - PricPsn:{}", resources);
        String bcn = DateTimeUtil.getDateTime("yyyyMMddHHmmss")+ (int) ((Math.random() * 9 + 1) * 1000);
        UserDetails userDetails = SecurityUtils.getCurrentUser();
        cn.hutool.json.JSONObject userJson = new cn.hutool.json.JSONObject(new cn.hutool.json.JSONObject(userDetails).get("user"));
        cn.hutool.json.JSONObject deptJson = new cn.hutool.json.JSONObject(userJson.get("dept"));
        log.info("sign deptJson:{}", deptJson);

        Long userId = SecurityUtils.getCurrentUserId();
        String nickName = SecurityUtils.getCurrentNickName();
        String username = SecurityUtils.getCurrentUsername();
        Long deptId = Long.parseLong(deptJson.getStr("id"));
        DeptDto deptDto = deptService.findById(deptId);



        String datetime = DateTimeUtil.getDateTime();

        resources.setNurscareOrgNo(deptDto.getDeptCode());
        resources.setUscc(deptDto.getUscc());

        List<String> psnTypeList = new ArrayList<>();
        psnTypeList.add(resources.getPsnTypeList());

        String input = "{\"data\": {" +
                "\"nurscare_org_no\":\""+resources.getNurscareOrgNo()+"\"," +
                "\"uscc\":\""+resources.getUscc()+"\"," +
                "\"nurscare_psn_name\":\""+resources.getNurscarePsnName()+"\"," +
                "\"nurscare_psn_cert_type\":\""+resources.getNurscarePsnCertType()+"\"," +
                "\"nurscare_psn_certno\":\""+resources.getNurscarePsnCertno()+"\"," +
                "\"nurscare_psn_gend\":\""+resources.getNurscarePsnGend()+"\"," +
                "\"nurscare_tel\":\""+resources.getNurscareTel()+"\"," +
                "\"psn_type_list\":" + psnTypeList + "," +
                "\"bank_majcls\":\"\"," +
                "\"bank_name\":\"\"," +
                "\"bank_id\":\"\"," +
                "\"bankacct\":\"\"," +
                "\"bank_acctname\":\"\"," +
                "\"admdvs\": \""+resources.getAdmdvs()+"\"," +
                "\"psn_nurscare_regn_ids\": \"\"}}";
        log.info("createPricPsn - input:{}", input);
        //签名
        String sign = SmUtilProvince.sign(input, deptDto);
        //加密
        String sm4Input = SmUtilProvince.encrypt(input, deptDto);

        String message = "{\"infno\": \"8301\"," +
                "\"msgid\": \"" + deptDto.getDeptCode() + ChsUtil.getMsgId() + "\"," +
                "\"mdtrtarea_admvs\": \"" + deptDto.getProvinceLicense() + "\"," +
                "\"insuplc_admdvs\": \"\"," +
                "\"recer_sys_code\": \"" + ChsInterfaceConfig.recerSysCode001 + "\"," +
                "\"dev_no\": \"\"," +
                "\"dev_safe_info\": \"\"," +
                "\"cainfo\": \"" + sign + "\"," +
                "\"signtype\": \"SM2\"," +
                "\"infver\": \"" + ChsInterfaceConfig.infver + "\"," +
                "\"opter_type\": \"1\"," +
                "\"opter\": \"" + SecurityUtils.getCurrentUserId() + "\"," +
                "\"opter_name\": \"" + SecurityUtils.getCurrentNickName() + "\"," +
                "\"inf_time\": \"" + DateUtil.format(DateUtil.date(), DatePattern.NORM_DATE_PATTERN) + "\"," +
                "\"fixmedins_code\": \"" + deptDto.getDeptCode() + "\"," +
                "\"fixmedins_name\": \"" + deptDto.getDeptName() + "\"," +
                "\"sign_no\": \"" + bcn + "\"," +
                "\"input\": \"" + sm4Input + "\"}";

        log.info("createPricPsn - message:{}", message);
        String encryptResult = httpNewMicProvince.handle(message, "护理人员新增", deptDto);
        log.info("createPricPsn - 护理人员新增:{}", encryptResult);
        JSONObject result = JSONObject.parseObject(encryptResult);
        if ("0".equals(result.getString("infcode"))) {
            String decryptionResult = SmUtilProvince.decryption(result.getString("output"), deptDto);
            log.info("createPricPsn - decryptionResult:{}", decryptionResult);


            String input8304 = "{\"data\": {" +
                    "\"nurscare_org_no\":\""+deptDto.getDeptCode()+"\"," +
                    "\"nurscare_org_id\": \""+deptDto.getOrgId()+"\"," +
                    "\"nurscare_org_name\": \""+deptDto.getDeptName()+"\"," +
                    "\"nurscare_psn_name\": \""+resources.getNurscarePsnName()+"\"," +
                    "\"nurscare_psn_cert_type\": \""+resources.getNurscarePsnCertType()+"\"," +
                    "\"nurscare_psn_certno\": \""+resources.getNurscarePsnCertno()+"\"," +
                    "\"page_num\": \"1\"," +
                    "\"page_size\": \"100\"," +
                    "\"admdvs\": \"\"}}";

            log.info("createPricPsn - input8304:{}", input8304);
            //签名
            String sign8304 = SmUtilProvince.sign(input8304, deptDto);
            //加密
            String sm4Input8304 = SmUtilProvince.encrypt(input8304, deptDto);

            String message8304 = "{\"infno\": \"8304\"," +
                    "\"msgid\": \"" + deptDto.getDeptCode() + ChsUtil.getMsgId() + "\"," +
                    "\"mdtrtarea_admvs\": \"" + deptDto.getProvinceLicense() + "\"," +
                    "\"insuplc_admdvs\": \"\"," +
                    "\"recer_sys_code\": \"" + ChsInterfaceConfig.recerSysCode001 + "\"," +
                    "\"dev_no\": \"\"," +
                    "\"dev_safe_info\": \"\"," +
                    "\"cainfo\": \"" + sign8304 + "\"," +
                    "\"signtype\": \"SM2\"," +
                    "\"infver\": \"" + ChsInterfaceConfig.infver + "\"," +
                    "\"opter_type\": \"1\"," +
                    "\"opter\": \"" + SecurityUtils.getCurrentUserId() + "\"," +
                    "\"opter_name\": \"" + SecurityUtils.getCurrentNickName() + "\"," +
                    "\"inf_time\": \"" + DateUtil.format(DateUtil.date(), DatePattern.NORM_DATE_PATTERN) + "\"," +
                    "\"fixmedins_code\": \"" + deptDto.getDeptCode() + "\"," +
                    "\"fixmedins_name\": \"" + deptDto.getDeptName() + "\"," +
                    "\"sign_no\": \"" + bcn + "\"," +
                    "\"input\": \"" + sm4Input8304 + "\"}";

            String encryptResult8304 = httpNewMicProvince.handle(message8304, "护理人员详情查询", deptDto);
            log.info("createPricPsn - encryptResult8304:{}", encryptResult8304);
            JSONObject result8304 = JSONObject.parseObject(encryptResult8304);
            if ("0".equals(result8304.getString("infcode"))) {

                String decryptionResult8304 = SmUtilProvince.decryption(result8304.getString("output"), deptDto);
                log.info("createPricPsn - decryptionResult8304:{}", decryptionResult8304);
                JSONObject output8304 = JSONObject.parseObject(decryptionResult8304);
                JSONArray dataArray8304 = output8304.getJSONArray("data");
                JSONObject psnObject = dataArray8304.getJSONObject(0);
                String nurscare_psn_no = psnObject.getString("nurscare_psn_no");
                String nurscare_psn_id = psnObject.getString("nurscare_psn_id");

                resources.setNurscarePsnNo(nurscare_psn_no);
                resources.setNurscarePsnId(nurscare_psn_id);
                resources.setSfyx("1");
                return new ResponseEntity<>(pricPsnService.create(resources),HttpStatus.CREATED);
            } else {
                return new ResponseEntity<>(result.getString("err_msg"), HttpStatus.OK);
            }



        } else {
            //return AjaxResult.error(result.getString("err_msg"));
            return new ResponseEntity<>(result.getString("err_msg"), HttpStatus.OK);
        }

    }

    @PutMapping
    @Log("修改护理员")
    @ApiOperation("修改护理员")
    @PreAuthorize("@el.check('pricPsn:edit')")
    public ResponseEntity<Object> updatePricPsn(@Validated @RequestBody PricPsn resources){
        pricPsnService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @DeleteMapping
    @Log("删除护理员")
    @ApiOperation("删除护理员")
    @PreAuthorize("@el.check('pricPsn:del')")
    public ResponseEntity<Object> deletePricPsn(@RequestBody String[] ids) {
        PricPsnDto pricPsnDto = pricPsnService.findById(ids[0]);


        log.info("deletePricPsn - resources:{}", pricPsnDto);

        String bcn = DateTimeUtil.getDateTime("yyyyMMddHHmmss")+ (int) ((Math.random() * 9 + 1) * 1000);
        UserDetails userDetails = SecurityUtils.getCurrentUser();
        cn.hutool.json.JSONObject userJson = new cn.hutool.json.JSONObject(new cn.hutool.json.JSONObject(userDetails).get("user"));
        cn.hutool.json.JSONObject deptJson = new cn.hutool.json.JSONObject(userJson.get("dept"));
        log.info("deletePricPsn - sign deptJson:{}", deptJson);

        Long userId = SecurityUtils.getCurrentUserId();
        String nickName = SecurityUtils.getCurrentNickName();
        String username = SecurityUtils.getCurrentUsername();
        Long deptId = Long.parseLong(deptJson.getStr("id"));
        DeptDto deptDto = deptService.findById(deptId);


        String input = "{\"data\": {" +
                "\"uscc\":\""+pricPsnDto.getUscc()+"\"," +
                "\"nurscare_psn_cert_type\":\""+pricPsnDto.getNurscarePsnCertType()+"\"," +
                "\"nurscare_psn_certno\": \""+pricPsnDto.getNurscarePsnCertno()+"\"}}";


        log.info("deletePricPsn - input:{}", input);
        //签名
        String sign = SmUtilProvince.sign(input, deptDto);
        //加密
        String sm4Input = SmUtilProvince.encrypt(input, deptDto);

        String message = "{\"infno\": \"8303\"," +
                "\"msgid\": \"" + deptDto.getDeptCode() + ChsUtil.getMsgId() + "\"," +
                "\"mdtrtarea_admvs\": \"" + deptDto.getProvinceLicense() + "\"," +
                "\"insuplc_admdvs\": \"\"," +
                "\"recer_sys_code\": \"" + ChsInterfaceConfig.recerSysCode001 + "\"," +
                "\"dev_no\": \"\"," +
                "\"dev_safe_info\": \"\"," +
                "\"cainfo\": \"" + sign + "\"," +
                "\"signtype\": \"SM2\"," +
                "\"infver\": \"" + ChsInterfaceConfig.infver + "\"," +
                "\"opter_type\": \"1\"," +
                "\"opter\": \"" + SecurityUtils.getCurrentUserId() + "\"," +
                "\"opter_name\": \"" + SecurityUtils.getCurrentNickName() + "\"," +
                "\"inf_time\": \"" + DateUtil.format(DateUtil.date(), DatePattern.NORM_DATE_PATTERN) + "\"," +
                "\"fixmedins_code\": \"" + deptDto.getDeptCode() + "\"," +
                "\"fixmedins_name\": \"" + deptDto.getDeptName() + "\"," +
                "\"sign_no\": \"" + bcn + "\"," +
                "\"input\": \"" + sm4Input + "\"}";

        String encryptResult = httpNewMicProvince.handle(message, "护理人员注销", deptDto);
        log.info("deletePricPsn - encryptResult:{}", encryptResult);
        JSONObject result = JSONObject.parseObject(encryptResult);
        if ("0".equals(result.getString("infcode"))) {
            String decryptionResult = SmUtilProvince.decryption(result.getString("output"), deptDto);

            PricPsn resources = new PricPsn();
            resources.setPricPsnId(ids[0]);
            resources.setSfyx("0");
            pricPsnService.update(resources);
            return new ResponseEntity<>(HttpStatus.OK);
        } else {
            //return AjaxResult.error(result.getString("err_msg"));
            return new ResponseEntity<>(result.getString("err_msg"), HttpStatus.OK);
        }
    }
}